import logging
from setting import LOGGING

class apispiderLog(object):
    def __init__(self):

        self.logger = logging.getLogger(__name__) # 日志器
        FORMATTERS = {} # 格式器
        HANDLERS = {}   # 处理器

        formatters_setting = LOGGING.get('formatters')
        handlers_setting = LOGGING.get('handlers')
        logger_setting = LOGGING.get('logger')

        for key in formatters_setting.keys():
            FORMATTERS[key] = logging.Formatter(formatters_setting[key].get('format'))


        for key in handlers_setting.keys():
            handler_level = 'logging.'+handlers_setting[key].get('level')
            handler_class = handlers_setting[key].get('class')
            handler_filename = handlers_setting[key].get('filename')
            handler_formatter = handlers_setting[key].get('formatter')
            handler_encoding = handlers_setting[key].get('encoding')
            if handler_class == 'logging.FileHandler':
                # 根据 配置文件创建 处理器 handler
                handler = logging.FileHandler(
                    filename=handler_filename,
                    encoding=handler_encoding,
                )
            elif handler_class == 'logging.StreamHandler':
                handler = logging.StreamHandler()

            handler.setLevel(eval(handler_level))
            handler.setFormatter(FORMATTERS[handler_formatter])
            HANDLERS[key] = handler

        self.logger.setLevel(logger_setting['level'])
        for hdlr in logger_setting['handlers']:
            self.logger.addHandler(HANDLERS[hdlr])

    def getlogger(self):
        return self.logger

# 测试
def test():
    logger = apispiderLog().getlogger()
    logger.debug('测试日志模块')
    logger.error('error')
    logger.info('hello')

# test()




